//
//  ZLRefreshControl.swift
//  我的微博
//
//  Created by Creator on 15/10/18.
//  Copyright © 2015年 Creator. All rights reserved.
//

import UIKit

private let kRefreshPullOffset: CGFloat = -60


class ZLRefreshControl: UIRefreshControl {

    // MARK: - 重写结束刷新方法
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopLoading()
    }
    
    // MARK: KVO 
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        //如果 y > 0 直接返回
        if frame.origin.y > 0 {
            
            return
        }
        
        
        // 判断是否开始刷新，如果进入刷新状态，播放加载动画
        if refreshing {
            refreshView.startLoading()
        } 
        
        if frame.origin.y < kRefreshPullOffset && !refreshView.rotateFlag{
//            print("翻过来")
            refreshView.rotateFlag = true
        } else if frame.origin.y > kRefreshPullOffset && refreshView.rotateFlag {
//            print("转过去")
           refreshView.rotateFlag = false
        }
    }
    

    
    // MARK: - 构造函数
  override  init() {
        super.init()
    
        setupUI()
    
    }

  required init?(coder aDecoder: NSCoder) {
      fatalError("init(coder:) has not been implemented")
  }
    
    
    deinit {
        self.removeObserver(self, forKeyPath: "frame")
    }
    
    
   
    
    // MARK: - 界面搭建
    private func setupUI() {
    
        
        
        // KVO 监听 frame 属性的变化
        self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        
        
        
        // 隐藏默认的转轮
        tintColor = UIColor.clearColor()
        
        // 添加刷新视图
        addSubview(refreshView)
        
        // 自动约束
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)
        
        
    }
    
    
    
    // MARK : 懒加载控件
    private lazy var refreshView: ZLRefreshView = ZLRefreshView.refreshView()
    
}


class ZLRefreshView: UIView {

    
   
    @IBOutlet weak var loadingIcon: UIImageView!
    @IBOutlet weak var tipView: UIView!
    @IBOutlet weak var tipIcon: UIImageView!
    
    ///  旋转标记
    private var rotateFlag = false {
        didSet {
            rotateTipIcon()
        }
    }
    
    
    ///  提示图标的旋转
    private func rotateTipIcon() {
        // 在快代码中，旋转会就近原则，默认顺时针寻找方向
        let angle = rotateFlag ? CGFloat(M_PI - 0.01) : CGFloat(M_PI + 0.01)
        
        UIView .animateWithDuration(0.25) { () -> Void in
            self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, angle)
        }
    
    }
    
    private func startLoading() {
        
        // 判断动画是否已经被添加
        if loadingIcon.layer.animationForKey("loadingAnim") != nil {
            return
        }
        
        // 隐藏 提示视图
        tipView.hidden = true
        
        // 定义动画
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 1.0
        
        // 添加动画
        loadingIcon.layer.addAnimation(anim, forKey: "loadingAnim")
        
    }
    
    ///  停止加载动画
    private func stopLoading() {
        tipView.hidden = false
        
        loadingIcon.layer.removeAllAnimations()
    }
    
    
    // 从 xib 加载刷洗in视图
    class func refreshView() -> ZLRefreshView {
        
        return NSBundle.mainBundle().loadNibNamed("ZLRefreshView", owner: nil, options: nil).last as! ZLRefreshView
        
    }
    
}
